<template>
  <el-tabs v-model="responseTabsValue" class="doc-tab" type="card" ref="tabsRef" :addable="addable" @tab-add="addTab"
    @tab-click="handleClick">
    <el-tab-pane v-for="item in responseTabs" :label="item.name + '(' + item.code + ')'" :key="item.id" :name="item.id">
      <div style="display: flex;justify-content: space-between;width: 98%;">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="名称:" prop="name">
            <div v-if="editor === false">{{ item.name }}</div>
            <el-input v-else v-model="item.name" @change="changeForm" placeholder="请输入响应名称"
              :disabled="editor === false" />
          </el-form-item>
          <el-form-item label="HTTP状态码:" prop="code">
            <div v-if="editor === false">{{ item.code }}</div>
            <el-select v-else v-model="item.code" @change="changeForm" placeholder="请选择HTTP状态码"
              :disabled="editor === false">
              <el-option v-for="codeitem in codeList" :key="codeitem.value" :label="codeitem.label"
                :value="codeitem.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <el-tooltip effect="dark" content="删除响应" placement="top" v-if="editor === true" >
          <el-button :icon="Delete" circle @click="deleteTab(item)" />
        </el-tooltip>
      </div>
      <div style="font-size: 14px;">数据结构</div>
      <EditResTable @change-edit-method="changeEditMethod" :editor="editor" :isenable="isenable"
        :data="apiResponseDataVOs" @table-data="handleTableData" />
    </el-tab-pane>
  </el-tabs>
  <!-- 添加响应弹窗 -->
  <responseForm ref="formRef" @success="updateDocument" :id="apiID" />
  <multipleEdit ref="multipleEditRef" :editorValue="editorValue" :isInstantUpdate="false"
    @update-editor-value="updateEditorValue" @text-to-json="handleTextToJSON" />
</template>
<script setup lang="ts">
import {
  Delete
} from '@element-plus/icons-vue'
import responseForm from './responseForm.vue'
import EditResTable from './EditResTable.vue';
import { propTypes } from '@/utils/propTypes'
import * as DebugApi from '@/api/debug'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const emit = defineEmits(['responseForm', 'update-document'])
const props = defineProps({
  data: propTypes.object.def({}),
  editor: propTypes.bool.def(),
  isenable: propTypes.bool.def()
})
const addable = props.editor

const tabsRef = ref(null);
const responseTabsValue = ref()
const responseTabs = ref([])
const codeList = ref([
  {
    label: '200',
    value: 200
  },
  {
    label: '201',
    value: 201
  },
  {
    label: '202',
    value: 202
  },
  {
    label: '204',
    value: 204
  },
  {
    label: '400',
    value: 400
  },
  {
    label: '401',
    value: 401
  },
  {
    label: '404',
    value: 404
  },
  {
    label: '500',
    value: 500
  },
  {
    label: '504',
    value: 504
  }
])

const updateDocument = async (data) => {
  emit('update-document', data)
}

/**
 * 新增响应
 * */
const formRef = ref()
const addTab = () => {
  formRef.value.open()
}

/**
 * 删除响应
 * */
const deleteTab = async (item) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DebugApi.deleteApiResponse({ id: item.id })
    message.success(t('common.delSuccess'))
    // 刷新列表
    emit('update-document', props.data)
  } catch { }
}

const responseTabsClick = ref()
const handleClick = (tab) => {
  responseTabsValue.value = tab.props.name
  responseTabsClick.value = responseTabsValue.value
  responseTabs.value.forEach((item) => {
    if (item.id === responseTabsValue.value) {
      apiResponseDataVOs.value = item.apiResponseDataVOs
    }
  })
  handleTableData(apiResponseDataVOs.value)
}

import multipleEdit from '../debug/dialog/MultipleEdit.vue'
import { JsonforData, DataforJson } from '@/utils/index'
const multipleEditRef = ref()
const apiResponseDataVOs = ref()
const editorValue = ref()
/**
 * 响应批量编辑
 * */
const changeEditMethod = (tableData) => {
  multipleEditRef.value.open(tableData)
}

/**
 * 表格全部数据
 * */
const handleTableData = (data) => {
  editorValue.value = JSON.stringify(DataforJson(data))
  apiResponseDataVOs.value = data
  responseTabs.value.forEach((item) => {
    if (item.id === responseTabsValue.value) {
      item.apiResponseDataVOs = apiResponseDataVOs.value
    }
  })
  emit('responseForm', responseTabs.value)
}
/**
 * 批量数据编辑后回显到表格
 * */
const updateEditorValue = (data) => {
  apiResponseDataVOs.value = JsonforData(JSON.parse(data))
  handleTableData(apiResponseDataVOs.value)
}
/**
 * 弹窗中text改变，触发editor改变
 * */
const handleTextToJSON = (data) => {
  editorValue.value = JSON.stringify(data)
}

const changeForm = () => {
  emit('responseForm', responseTabs.value)
}
const apiID = ref()
const init = () => {
  if (props.data.id) {
    responseTabs.value = props.data.responseinfo
    responseTabs.value.forEach((item) => {
      if (item.apiResponseDataVOs === null) {
        item.apiResponseDataVOs = [{ keyName: 'root', keyValue: '', keyType: 'object' }]
      } else if (item.apiResponseDataVOs != null && typeof item.apiResponseDataVOs === 'string') {
        item.apiResponseDataVOs = JSON.parse(item.apiResponseDataVOs)
      }
    })
    apiID.value = props.data.id
  }
}
watch(() => props.data, () => {
  init()
}, {
  deep: true
})
watch(() => props.data.responseinfo.length, () => {
  init()
  responseTabsValue.value = responseTabs.value[responseTabs.value.length - 1].id
  apiResponseDataVOs.value = responseTabs.value[responseTabs.value.length - 1].apiResponseDataVOs
}, {
  deep: true
})
onMounted(() => {
  init()
  responseTabsValue.value = responseTabs.value[0].id
  apiResponseDataVOs.value = responseTabs.value[0].apiResponseDataVOs
})
</script>

<style lang="scss">
.doc-tab {
  .el-tabs__new-tab {
    margin-right: 10px !important;
  }
}

.demo-form-inline {
  .el-input {
    --el-input-width: 100px;
  }

  .el-select {
    --el-select-width: 80px;
  }

  .el-select__wrapper,
  .el-select__wrapper:hover,
  .el-select__wrapper.is-hovering:not(.is-focused),
  .el-input__wrapper,
  .el-input__wrapper:hover {
    box-shadow: none;
  }

  .el-select__wrapper:hover,
  .el-input__wrapper:hover {
    background-color: rgb(244, 246, 248);
  }
}
</style>
